package index;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "AuthenticationFilter", urlPatterns = "/*")
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 使用更准确的路径获取方式
        String path = httpRequest.getServletPath();

        // 允许公开访问的资源
        boolean allowAccess = path.equals("/index.jsp")
                || path.startsWith("/loginRegister")
                || path.startsWith("/Captcha")
                || path.startsWith("/Register")
                || path.startsWith("/Login")
                || path.startsWith("/Welcome")
                || path.startsWith("/Logout") // 添加退出路径
                || path.startsWith("/FileUpload")
                || path.startsWith("/error");

        if (allowAccess) {
            chain.doFilter(request, response);
            return;
        }

        // 检查会话状态
        HttpSession session = httpRequest.getSession(false);
        if (session == null || session.getAttribute("username") == null) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/loginRegister.jsp");
        } else {
            // 管理员路径检查
            boolean isAdminResource = path.startsWith("/admin")
                    || path.equals("/FileUploadServlet") // 精确匹配Servlet路径
                    || path.equals("/AdminDishListServlet");

            if (isAdminResource) {
                String role = (String) session.getAttribute("role");
                if (!"admin".equals(role)) {
                    httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "权限不足");
                    return;
                }
            }

            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}
}
